﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Excel;

namespace OrderAggregator.InputFormats.Art
{
	/// <summary>
	/// Формат ООО" Компания АРТ"
	/// </summary>
	public class ArtFormat : Excel.BaseExcelFormat
	{
		const int КолонкаНаименованияТовара = 3;

        public readonly static ArtFormat Instance = new ArtFormat();

        private ArtFormat()
        {
        }
		
		/// <summary>
		/// Parse
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="getStream"></param>
		/// <returns></returns>
		public override BaseOrder Parse(string filePath, Func<System.IO.Stream> getStream)
		{
			if (!string.Equals(System.IO.Path.GetExtension(filePath), dotXLS, StringComparison.InvariantCultureIgnoreCase))
			{
				return null;
			}	

            DataTable table;
            try
            {
                //var dataSet = ReadAsDataset(getStream());

                //if (dataSet == null || dataSet.Tables.Count == 0)
                //{
                //    return null;
                //}

                //table = dataSet.Tables[0];           
                table = ReadAsDataTable(Path.GetFullPath(filePath));
            }
            catch
            {
                return null;
            }

			string number;
			DateTime date;
            if (!TryParseNumberAndDate(table, out number, out date))
			{
				return null;
			}

			var order = new BaseOrder();
			order.Id = number;
			order.ReceiveTime = date;
			order.Client = table.Rows[6][5] as string;

			var orderDataRows = GetOrderRows(table);

			foreach (var orderDataRow in orderDataRows)
			{
				var orderRow = new BaseOrderRow();

				var productName = orderDataRow[КолонкаНаименованияТовара] as string;

				if (string.IsNullOrEmpty(productName))
				{
					productName = string.Empty;
				}

				productName = productName.Replace("Шустова", "").Trim();

				orderRow.ProductName = productName;
				orderRow.ProductCode = productName; //нет кода

				orderRow.Count = Convert.ToDecimal(orderDataRow[20]);
				orderRow.UnitName = orderDataRow[23] as string;

				order.OrderRows.Add(orderRow);
			}

			return order;
		}

        private bool TryParseNumberAndDate(DataTable table, out string number, out DateTime date)
		{
            number = string.Empty;
            date = DateTime.MinValue;

            if (table.Rows.Count < 3)
            {
                return false; 
            }


			string header = table.Rows[2][1] as string;

            if (string.IsNullOrEmpty(header))
            {
                return false;
            }

			const string header1 = "Заказ поставщику №";

			int index = header.IndexOf(header1);

			if (index < 0)
			{
				return false;
			}

			header = header.Substring(index + header1.Length);

			const string header2 = "от";

			index = header.IndexOf(header2);

			if (index < 0)
			{
				return false;
			}

			number = header.Substring(0, index).Trim();
			date = DateTime.Parse(header.Substring(index + header2.Length), RuCulture);

			return true;


		}

		private static List<DataRow> GetOrderRows(DataTable table)
		{
			var rows = new List<DataRow>();

			int startRow = -1;

			for (int i = 6; i < table.Rows.Count; i++)
			{
				var row = table.Rows[i];

				var strColmn1 = row[КолонкаНаименованияТовара] as string;
				

				if (!string.IsNullOrEmpty(strColmn1) && strColmn1.Contains("Товары (работы, услуги)"))
				{
					startRow = i + 2;
					break;
				}
			}

			if (startRow < 0)
			{
				return rows;
			}

			for (int i = startRow; i < table.Rows.Count; i++)
			{
				var row = table.Rows[i];

				var strColmn1 = row[КолонкаНаименованияТовара] as string;

				if (string.IsNullOrEmpty(strColmn1))
				{
					break;
				}

				rows.Add(row);
			}

			return rows;
		}
		
	}
}
